package com.ctz.commonframe.ui.widget;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class AdapterViewHolder {
	private SparseArray<View> views;
	private int position;
	private View convertView;

	private AdapterViewHolder(Context context, ViewGroup parent, int layoutId, int position) {
		this.position = position;
		this.views = new SparseArray<View>();
		convertView = LayoutInflater.from(context).inflate(layoutId, parent, false);
		convertView.setTag(this);
	}

	public static AdapterViewHolder getInstance(Context context, View convertView, ViewGroup parent, int layoutId, int position) {
		if (convertView == null) {
			return new AdapterViewHolder(context, parent, layoutId, position);
		} else {
			AdapterViewHolder holder = (AdapterViewHolder) convertView.getTag();
			holder.position = position;
			return holder;
		}
	}

	public View getConvertView() {
		return convertView;
	}

	/**
	 * 获取ListView的当前位置
	 * 
	 * @return 当前位置
	 */
	public int getPosition() {
		return position;
	}

	/**
	 * 通过viewId获取控件
	 * 
	 * @param viewId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T extends View> T getView(int viewId) {
		View view = views.get(viewId);
		if (view == null) {
			view = convertView.findViewById(viewId);
			views.put(viewId, view);
		}
		return (T) view;
	}
}
